import {createRouter, createWebHistory, RouteRecordRaw} from 'vue-router'
import Layout from '../components/layout/index.vue'

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        name: 'Login',
        path: '/login',
        component: () => import('../pages/login.vue')
    },
    {
        name: 'Home',
        path: '/home',
        redirect: '/home/index',
        component: Layout,
        children: [
            {
                name: 'HomeIndex',
                path: '/home/index',
                component: () => import('../pages/home.vue')
            }
        ]
    },
    {
        name: 'UICom',
        path: '/uicom',
        component: Layout,
        children: [
            {
                name: 'UIComTable',
                path: '/uicom/table',
                component: () => import('../pages/table.vue')
            },
            {
                name: 'UIComForm',
                path: '/uicom/form',
                component: () => import('../pages/form.vue')
            }

        ]
    }
]

const router = createRouter({
    scrollBehavior: () => ({left: 0, top: 0}),
    history: createWebHistory(),
    routes
})

const hasLogin = ():Boolean  => {
    let isLogin = false
    const user = localStorage.getItem('user') 
    if(user) isLogin = true
    return isLogin

}
const whiteRoutes = <any>['Login'];
router.beforeEach((to, from, next) => {  
    if(whiteRoutes.includes(to.name)){
        next()
    }else{
        if(hasLogin()){
            next()
        }else{  
            next({
                name: 'Login'
            })
        }
    }
})

export default router



